package cn.net.trimmer.servlet.demo1.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.net.trimmer.servlet.demo1.entity.User;
import cn.net.trimmer.servlet.demo1.service.UserService;
import cn.net.trimmer.servlet.demo1.util.Factory;

public class UserHttpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 获取用户服务
	private Factory<UserService> fa = new Factory<>();
	private UserService us = fa.createBean("userService");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置响应数据类型和编码格式
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		// 设置接收参数的类型及编码
		// req.setCharacterEncoding("utf-8");
		// get方式处理中文乱码
		String username = new String(req.getParameter("username").getBytes("ISO-8859-1"), "UTF-8");
		String password = req.getParameter("password");
		User user = us.login(username, password);

		// 获取响应流
		PrintWriter out = resp.getWriter();
		out.print("<html>");
		if (user == null) {
			out.print("<body><h1>登录失败</h1></body>");
		} else {
			out.print("<body><h1>登录成功+" + new Date() + "</h1></body>");
		}
		out.print("</html");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置响应数据类型和编码格式
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		// post方式解決中文乱码
		req.setCharacterEncoding("utf-8");

		String username = req.getParameter("username");
		String password = req.getParameter("password");
		User user = us.login(username, password);

		// 获取响应流
		PrintWriter out = resp.getWriter();
		out.print("<html>");
		if (user == null) {
			out.print("<body><h1>登录失败</h1></body>");
		} else {
			out.print("<body><h1>登录成功+" + new Date() + "</h1></body>");
		}
		out.print("</html");
	}

}
